package com.ansion.basedb.database;

import com.ansion.basedb.database.kdf.HKDF;
import com.ansion.utils.hash.Base64Helper;

import java.nio.charset.StandardCharsets;

public class DatabaseKeyGenerator {

    public static class DatabaseKeyResult {
        public byte[] keyData;
        public String base64EncodedKey;
        public Exception error;
    }

    public static DatabaseKeyResult generateDatabaseKeyForUID(String uid) {
        DatabaseKeyResult resultObject = new DatabaseKeyResult();

        if (uid == null || uid.isEmpty()) {
            resultObject.error = new Exception("Invalid UID: UID must be a non-empty string.");
            return resultObject;
        }

        byte[] seed = new byte[]{(byte) 0xe7, (byte) 0x96, 0x06, 0x5e, 0x1e, (byte) 0xee, (byte) 0xf5, 0x6e, 0x20, (byte) 0x82, (byte) 0xe5, (byte) 0xc7, (byte) 0xc6, (byte) 0xb2, (byte) 0xff, (byte) 0xec, 0x0e, 0x46, 0x62, (byte) 0xe7, 0x25, (byte) 0x8e, (byte) 0xc2, (byte) 0xf3, (byte) 0xdf, (byte) 0x99, 0x17, (byte) 0xe4, (byte) 0xb7, 0x64, (byte) 0xad, 0x1f};
        byte[] info = uid.getBytes(StandardCharsets.UTF_8);
        byte[] salt = new byte[]{0x12, (byte) 0x9d, (byte) 0x84, 0x1d};
        int outputSize = 32;
        try {
            byte[] keyData = HKDF.deriveSecrets(seed, salt, info, outputSize);
            if (keyData == null || keyData.length != outputSize) {
                resultObject.error = new Exception("Failed to generate key data.");
                return resultObject;
            }

            String base64EncodedKey = Base64Helper.encode(keyData);
            resultObject.keyData = keyData;
            resultObject.base64EncodedKey = base64EncodedKey;
        } catch (Exception e) {
            resultObject.error = e;
        }

        return resultObject;
    }

}
